﻿namespace OkFlurl
{
    public class FlurlProgress
    {
        private IProgress<ProgressData> Progress { get; }

        public FlurlProgress(Action<ProgressData> action)
        {
            Progress = new Progress<ProgressData>(action);
        }

        public void Change(long? length, long readLength, double percent)
        {
            Progress.Report(new ProgressData { Total = length, Read = readLength, Percent = percent });
        }

        public void Change(ProgressData data)
        {
            Progress.Report(data);
        }

        internal bool IsStop { get; set; }

        public string FileName { get; set; }

        internal CancellationTokenSource Cts;

        public CancellationToken Token { get; set; }

        internal async Task WaitAsync()
        {
            try
            {
                await Task.Delay(int.MaxValue, Cts.Token).ConfigureAwait(false);
            }
            catch
            {

            }
        }

        public void Init(bool stop)
        {
            IsStop = stop;
            if (IsStop)
            {
                Cts = new();
            }
        }

        public void Close()
        {
            try
            {
                Cts?.Cancel();
            }
            catch { }

            try
            {
                Cts?.Dispose();
            }
            catch
            {

            }

            IsStop = false;
        }

        public void Start()
        {
            if (Token.IsCancellationRequested)
            {
                Close();
                Token.ThrowIfCancellationRequested();
            }

            if (!IsStop)
            {
                return;
            }

            IsStop = false;
            Close();
        }

        public void Stop()
        {
            if (Token.IsCancellationRequested)
            {
                Close();
                Token.ThrowIfCancellationRequested();
            }

            if (IsStop)
            {
                return;
            }

            Cts = new();
            IsStop = true;
        }
    }
}
